package com.telit.communicate.communicate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author zhouyu
 * @description 用户实例缓存（外层只读不写，无需考虑线程安全问题）
 **/
public class UserInstanceCache {

    /**
     * list存放容器
     */
    private static final Map<String, List<ConcurrentHashMap<Object, Object>>> INSTANCE_CACHE = new HashMap<>();

    /**
     * 实例个数
     */
    private final static int COUNT = 10;

    /**
     * 实例存放list
     */
    private static List<ConcurrentHashMap<Object, Object>> INSTANCE_LIST = null;

    /**
     * ConcurrentHashMap实例
     */
    private static ConcurrentHashMap<Object, Object> INSTANCE_INFO = null;


    /**
     * 创建容器
     *
     * @param instanceName 容器名
     */
    public static void createInstanceCache(String instanceName) {
        INSTANCE_LIST = new ArrayList<>();
        for (int i = 0; i < COUNT; i++) {
            INSTANCE_INFO = new ConcurrentHashMap<>();
            INSTANCE_LIST.add(INSTANCE_INFO);
        }
        INSTANCE_CACHE.put(instanceName, INSTANCE_LIST);
    }

    /**
     * 根据容器名获取容器实例
     *
     * @param instanceName 容器名
     * @return 容器实例
     */
    public static List<ConcurrentHashMap<Object, Object>> getCacheInstance(String instanceName) {
        return INSTANCE_CACHE.get(instanceName);
    }

    /**
     * 获取容器对应数据
     *
     * @param instanceName 容器名
     * @param key          键
     * @return 值
     */
    public static Object getValueFromCache(String instanceName, Object key) {
        return INSTANCE_CACHE.get(instanceName).get(Math.abs(key.hashCode()) % COUNT).get(key);
    }

    /**
     * 添加键值对到容器
     *
     * @param instanceName 容器名
     * @param key          键
     * @param value        值
     */
    public static void setValueToCache(String instanceName, Object key, Object value) {
        INSTANCE_CACHE.get(instanceName).get(Math.abs(key.hashCode()) % COUNT).put(key, value);
    }

    /**
     * 从容器删除键值对
     *
     * @param instanceName 容器名
     * @param key          键
     */
    public static void removeCacheByKey(String instanceName, Object key) {
        INSTANCE_CACHE.get(instanceName).get(Math.abs(key.hashCode()) % COUNT).remove(key);
    }

    /**
     * 删除所有缓存数据
     */
    public static void clearAllCache() {
        INSTANCE_CACHE.clear();
    }
}
